package com.hs.sfzy.controller;

import com.github.pagehelper.PageInfo;
import com.hs.sfzy.entity.User;
import com.hs.sfzy.service.UserService;
import com.hs.sfzy.until.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author wangzhihao
 * @Date 2025年08月12日 21:14
 * @Version 1.0
 */
@RestController
@RequestMapping("User")
public class UserController {
    @Autowired
    private UserService userService;
    // 登录功能
    @GetMapping("login")
    public R login(String account, String password){
        User user = userService.login(account, password);
        if(user != null){
            return R.ok(user);
        }else{
            return R.fail("账号或密码有误！");
        }
    }

    // 增加
    @PostMapping
    public R addUser(@RequestBody User user) {
        int i = userService.addUser(user);
        if (i > 0) {
            return R.ok("添加成功！");
        }else {
            return R.fail();
        }
    }
    // 修改
    @PutMapping
    public R updateUser(@RequestBody User user) {
        int i = userService.updateUser(user);
        if (i > 0) {
            return R.ok("修改成功！");
        }else {
            return R.fail();
        }
    }
    // 根据id删除
    @DeleteMapping("{id}")
    public R deleteUser(@PathVariable("id") int id) {
        int i = userService.deleteUser(id);
        if (i > 0) {
            return R.ok("删除成功！");
        }else{
            return R.fail();
        }
    }
    // 根据id查询
    @GetMapping("{id}")
    public R getUserById(@PathVariable("id") int id) {
        User user = userService.findUserById(id);
        return R.ok(user);
    }
    // 分页查询
    @GetMapping("page")
    public R getUsers(User user,
                      @RequestParam(required = false,defaultValue = "1")int pageNum,
                      @RequestParam(required = false,defaultValue = "2")int pageSize){
        PageInfo<User> pageInfo = userService.findUsers(user, pageNum, pageSize);
        return R.ok(pageInfo);
    }
    @PutMapping("update")
    public R update(@RequestBody User user) {
        int i = userService.updateUser(user);
        if (i > 0) {
            return R.ok("修改成功！");
        }else {
            return R.fail();
        }
    }

}
